<!--
 * @company : 版权所属 四川北星惯牌科技有限公司
 * @contact : 刘经理 19326416371
 -->
<template>
	<view class="main-box w100 flex-row-center" style="display: flex;height: 100vh;">
		<view class="head-box" :style="{paddingTop: +statusBarHeight+'px'}">
			<view class="head-title flex-row-center">
				<text class="title">首页</text>
				<view class="address-box flex-row-center" @click="chooseLocationTap">
					<up-icon name="map" color="rgba(255,255,255,0.87)" size="20"></up-icon>
					<template>
						<text class="address"
							v-if="addressInfo&&addressInfo.districtInfo">{{addressInfo.districtInfo}}</text>
						<text class="address" v-else>定位失败</text>
					</template>
					<up-icon name="arrow-right" color="rgba(255,255,255,0.87)" size="12"></up-icon>
				</view>

			</view>
			<!-- 搜索 -->
			<!-- 	<view class="search-box">
				<up-search placeholder="请输入搜索名称" height="72rpx" placeholderColor="#C0CCCF" searchIconColor="#C0CCCF"
					bgColor="rgba(255,255,255,0.2)" :inputStyle="inputStyle" style="" :showAction='false'
					v-model="keyword"></up-search>
			</view> -->
			<!-- 轮播图 -->

		</view>
		<!-- 内容 style="margin-top: 426rpx;" -->
		<view class="main-content w100" >
			<scroll-view :scroll-top="scrollTop" @refresherrefresh="onRefresh" refresher-default-style="white"
				:refresher-enabled="true" @refresherpulling="onPpulling" scroll-y="true" @refresherrestore="onRestore"
				:refresher-triggered="groupInfo.triggered" style="width: 100%;height: 100%;" class="scroll-Y">
				<view class="swiper-box w100">
					<template v-if="information">
						<up-swiper :list="information" keyName="image" height="300rpx" radius="16rpx" indicator
							indicatorMode="line" circular></up-swiper>
					</template>
				</view>
				<!-- 导航入口 -->
				<view class="navigation-box w100">
					<view class="navigation-item" v-for="(item,index) in navigationList" :key="index"
						@click="toNavigation(item)">
						<text :class="[item.icon,'iconfont  icon']"></text>
						<text class="name">{{item.name}}</text>
					</view>
				</view>
				<!-- list -->
				<view class="team-list">
					<template v-if="itemLoading">
						<view class="team-list-item" v-for="num in 3" :key="num">
							<uv-skeletons loading :skeleton="skeleton"></uv-skeletons>
						</view>
					</template>
					<template v-else>
						<template v-if="groupInfo.list.length>0">
							<teamItem :teamInfo="item" v-for="(item,index) in groupInfo.list" :key="item.t_id">
							</teamItem>
							<view class="view-more">
								<up-loadmore :status="groupInfo.status" />
							</view>
						</template>
						<view class="not-list-view" v-else>
							<text class="text">暂无相关类型数据~</text>
						</view>
					</template>

				</view>
			</scroll-view>
		</view>
		<!-- 未登录导航入口 -->
		<noLoginNavVue></noLoginNavVue>
		<!-- 底部tabbar -->
		<tabbarContentVue :current="0"></tabbarContentVue>
	</view>
	<up-popup :show="noticeShow" :safeAreaInsetBottom="false" round="18rpx" closeable bgColor="#222528" mode="center"
		@close="closeShow">
		<view class="notice-content  flex-row-center" v-if="noticeInfo">
			<text class="name ">公告通知</text>
			<view class="content-box w100 flex-row-center">
				<view class="notice-box w100 flex-row-center" v-if="noticeInfo">
					<scroll-view scroll-y="true" class="scroll-Y">
						<view class="w100 flex-row-center" style="flex-direction: column;">
							<text class="title">{{noticeInfo.title}}</text>
							<view class="content w100">
								<up-parse :tagStyle="tagStyles" :content="noticeInfo.content"></up-parse>
							</view>
							<text class="time">{{noticeInfo.create_time_text}}</text>
						</view>
					</scroll-view>
				</view>
			</view>
			<view class="notice-btn" @click="closeShow">
				<text class="text">我知道了</text>
			</view>
		</view>
	</up-popup>
</template>

<script setup>
	import {
		getLocationInf
	} from '@/utils/getLocation.js';
	import {
		themeStore
	} from '@/stores/theme.js';
	import {
		chooseLocation
	} from '@/utils/chooseLocation';
	import {
		userInfoStore
	} from '@/stores/user';
	import tabbarContentVue from '@/components/tabbarContent/tabbarContent.vue';
	import teamItem from '@/components/main/teamItem.vue';
	import noLoginNavVue from '@/components/noLoginNav/noLoginNav.vue';
	import {
		handleDistance,
		countDown,
		isMillisecondTimestamp,
		parseURLParams3
	} from '@/utils/utools.js';
	import {
		configInfoStore
	} from '@/stores/config.js';
	import {
		inviteInfoStore
	} from '@/stores/inviteInfo';
	const inviteStore = inviteInfoStore();
	const configStore = configInfoStore();
	const tagStyles = {
		p: "color:#dedede;font-size:24rpx;line-height:42rpx;",
		span: "color:#dedede;font-size:24rpx;line-height:42rpx;",
		div: "color:#dedede;font-size:24rpx;line-height:42rpx;",
		img: "max-width:480rpx;",
		image: "max-width:480rpx;",
	};
	const skeleton = [{
			type: 'flex',
			num: 1,
			style: 'alignItems: center',
			children: [{
				type: 'custom',
				num: 1,
				style: 'width:68rpx;height:68rpx;marginRight: 16rpx;borderRadius:50%;'
			}, {
				type: 'line',
				num: 1,
				style: 'width:100%;',
			}]
		},
		{
			type: 'flex',
			num: 1,
			style: 'marginTop:24rpx;marginBottom:24rpx;display:flex;',
			children: [{
					type: 'custom',
					num: 1,
					style: 'width:226rpx;height:226rpx;borderRadius:16rpx;marginRight: 34rpx;'
				},
				{
					type: 'line',
					num: 3,
					gap: '20rpx'
				},

			]
		}, {
			type: 'line',
			num: 1,
			gap: '20rpx'
		}
	]
	const userStore = userInfoStore();
	const theme = themeStore();
	const inputStyle = {
		color: '#C0CCCF'
	};
	const status = ref('loading');
	const itemLoading = ref(true);
	const information = ref(null)
	const addressInfo = computed(() => userStore.addressInfo);
	let tabLists = [{
		name: '全部',
		label: 0
	}]
	const tabList = ref(computed(() => userStore.level_info?.tabList || tabLists));
	const navigationList = [{
		name: '组队邀请',
		icon: 'icon-130',
		url: '/page_main/views/mainTeamList'
	}, {
		name: '赛事活动',
		icon: 'icon-saishi',
		url: '/page_main/views/mainMatchList'
	}, {
		name: '助教中心',
		icon: 'icon-zhujiaogongzuotai',
		url: '/pages/active/active'
	}, {
		name: '参与培训',
		icon: 'icon-peixunzhuanqu',
		url: '/page_user/views/submitTrain'
	}, ];
	const groupInfo = reactive({
		list: [],
		page: 1,
		status: 'loadmore',
		triggered: false,
	})

	const keyword = ref('');
	const noticeInfo = ref(null);
	const noticeShow = ref(false);
	const subsectionIndex = reactive({
		level: 0, //等级，默认全部
		type: 1, //最近，最新
	});
	const statusBarHeight = ref(0);
	const scrollTop = ref(0.01);
	const toPayment = () => {
		uni.navigateTo({
			url: '/pages/payment/payment'
		})
	}
	onLoad(async (option) => {
		statusBarHeight.value = uni.getSystemInfoSync().statusBarHeight;
		// 获取位置信息
		getAddressInfo();
		let user_token = uni.getStorageSync('user_token');
		userStore.getLevelList();
		// getLevelList();
		getInformation();
		getNewNotice();
		setTimeout(() => {
			itemLoading.value = false;
		}, 3000)
		if (option.i && option.t) {
			inviteStore.setInviteInfo(option.i, option.t);
		}
		if (option.scene) { //小程序码分享
			let url = '?' + decodeURIComponent(option.scene);
			let parameter = parseURLParams3(url);
			inviteStore.setInviteInfo(parameter.i, parameter.t);
		}
	})
	onShow(() => {
		// addressInfo.value = userStore.addressInfo;
	})
	const onRefresh = () => { //下拉刷新
		if (groupInfo.triggered) return;
		groupInfo.triggered = true;
		restList();
	}
	const getmainGroupList = async (lat, lng) => { //获取组队列表
		const res = await $Api.group.getmainGroupList({
			page: groupInfo.page,
			type: subsectionIndex.type,
			level: subsectionIndex.level,
			lat: addressInfo.value?.latitude,
			lng: addressInfo.value?.longitude
		})
		setTimeout(() => { //重置下拉刷新
			itemLoading.value = false;
			groupInfo.triggered = false;
		}, 800)
		if (res.code === 1) {

			if (res.data.list && res.data.list.length > 0) {
				let arr = [];
				arr = res.data.list.map(val => {
					let imageList = [];
					let fristName = '北';
					let countDownInfo = {
						status: -1,
						timeInfo: {}
					}
					if (val.juli) {
						val.juli = handleDistance(val.juli);
					}
					if (val.image) {
						if (typeof val.image === 'string') {
							imageList = val.image.split(',');
						} else if (Array.isArray(val.image)) {
							val.image.forEach(item => {
								imageList.push(item.url);
							})
						}
					};
					if (val.nickname) {
						fristName = val.nickname.charAt(0)
					}
					countDownInfo = computeDate(val.start_date, val.end_date)
					return {
						...val,
						imageList: imageList,
						fristName,
						countDownInfo
					}
				})
				groupInfo.list = [...groupInfo.list, ...arr];
			}
			if (res.data.totalPage > groupInfo.page) {
				groupInfo.status = 'loadmore';
				groupInfo.page++;
			} else {
				groupInfo.status = 'nomore';
			}
			// console.log('groupInfo.list', groupInfo.list);
		} else {
			setTimeout(() => {
				groupInfo.triggered = false;
			}, 800)
			uni.$u.toast(res.msg);
		}
	};
	const computeDate = (startDate, endDate) => {
		if (!isMillisecondTimestamp(startDate)) { //判断毫秒级时间戳
			startDate = startDate * 1000
		}
		if (!isMillisecondTimestamp(endDate)) { //判断毫秒级时间戳
			endDate = endDate * 1000
		}
		let newDate = new Date().getTime();
		if (newDate > endDate) { //已经结束
			return {
				status: -1,
				timeInfo: {}
			}
		} else if (newDate > startDate && newDate <= endDate) { //进行中，距结束多少时间
			let obj = {}
			obj = countDown(endDate);
			return {
				status: 1,
				...obj
			}
		} else if (newDate <= startDate) { //未开始 距开始多少时间
			let obj = {}
			obj = countDown(startDate);
			return {
				status: 2,
				...obj
			}
		}
	}
	const getNewNotice = async () => { //获取最新公告
		const res = await $Api.user.getNewNotice();
		if (res.code == 1 && res.data) {
			let id = uni.getStorageSync('current_notice_id');
			if (id && id == res.data.id) {
				return
			}
			noticeShow.value = true;
			noticeInfo.value = res.data;
			uni.setStorageSync('current_notice_id', res.data.id);
		}
	}
	const getInformation = async () => {
		const res = await $Api.main.getInformation();
		if (res.code == 1) {
			information.value = res.data.list;
		} else {

		}
	}
	const closeShow = () => {
		noticeShow.value = false;
		noticeInfo.value = null;
	}
	const toNotice = () => {
		uni.navigateTo({
			url: "/page_user/views/noticeList"
		})
	}
	const changeSubsection = (item, index) => { //切换Subsection
		if (subsectionIndex.type === item.label) return;
		subsectionIndex.type = item.label;
		groupInfo.triggered = false; //关闭下拉刷新
		restList();
	}
	const changeTab = (e) => {
		subsectionIndex.level = e.label;
		groupInfo.triggered = false; //关闭下拉刷新
		restList();
	}
	const restList = () => { //重置列表
		groupInfo.list = [];
		groupInfo.page = 1;
		groupInfo.status = 'loadmore';
		itemLoading.value = true;
		if (scrollTop.value == 0.01) { //执行滚动
			scrollTop.value = 0.011
		} else {
			scrollTop.value = 0.01;
		}
		getmainGroupList();
	}

	const getAddressInfo = async () => { //获取当前位置信息
		try {
			const res = await getLocationInf();
			if (res.latitude && res.longitude) {
				userStore.addressInfo = res;
				getmainGroupList(res.latitude, res.longitude);
				userStore.setUserAddress({ //给用户设置默认地区
					lat: res.latitude,
					lng: res.longitude
				});
			} else if (userStore.addressInfo) {
				let data = userStore.addressInfo;
				getmainGroupList(data?.latitude, data?.longitude);
				userStore.setUserAddress({ //给用户设置默认地区
					lat: data.latitude,
					lng: data.longitude
				});
			}
		} catch (e) {
			getmainGroupList();
		}

	}
	const toNavigation = (item) => {
		if (!item.url) return;

		if (item.name === '助教中心') {
			uni.switchTab({
				url: '/pages/activity/activity'
			});
			return;
		}
		uni.navigateTo({
			url: item.url
		})
	}
	const chooseLocationTap = async () => { //选择地理位置
		// userStore.setAddressInfo();
		const res = await chooseLocation(userStore.addressInfo?.latitude, userStore.addressInfo?.longitude);
		console.log(res);
		if (res.districtInfo) {
			userStore.addressInfo = res;
			restList();
		}
	}
	watch(() => userStore.addressInfo, (newVal) => {
		// console.log('地址信息变化了', newVal);
	})
</script>
<style lang="scss">
	.u-search__content__input {
		background-color: transparent !important;
	}
</style>
<style lang="scss" scoped>
	.head-title {
		height: 76rpx;
		box-sizing: border-box;
		padding: 0 40rpx;

		.title {
			font-weight: 800;
			font-size: 44rpx;
			color: #FFFFFF;
		}

		.address-box {
			margin-left: 30rpx;

			.address {
				max-width: 178rpx;
				height: 36rpx;
				font-weight: 500;
				font-size: 26rpx;
				color: rgba(255, 255, 255, 0.87);
				text-overflow: ellipsis;
				white-space: nowrap;
				overflow: hidden;
				margin: 0 6rpx;
			}
		}
	}

	.search-box {
		width: 100%;
		box-sizing: border-box;
		margin: 20rpx 0;
		padding: 0 14rpx;
	}

	.swiper-box {
		height: 300rpx;
		padding: 0 20rpx;
	}

	.navigation-box {
		margin-top: 20rpx;
		padding: 0 20rpx;
		display: grid;
		grid-template-columns: repeat(2, 1fr);
		row-gap: 20rpx;
		column-gap: 20rpx;

		.navigation-item {
			align-items: center;
			border-radius: 12rpx;
			box-sizing: border-box;
			display: flex;
			background-color: rgba(122, 222, 207, .2);
			padding: 12rpx 36rpx;

			.icon {
				color: #94DEAC;
				font-size: 62rpx;
				background: -webkit-linear-gradient(270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%);
				background: linear-gradient(270deg, #94DEAC 0%, #7CDEC7 47%, #79DED3 100%);
				-webkit-background-clip: text;
				background-clip: text;
				-webkit-text-fill-color: transparent;
				color: transparent;
			}

			.name {
				color: $name-color;
				font-size: 30rpx;
				font-weight: bold;
				margin-left: 38rpx;
			}
		}
	}

	.team-list {
		box-sizing: border-box;
		width: 100%;
		padding: 0 20rpx;
		// margin-top: 24rpx;
		margin-top: 12rpx;
	}

	.main-box {
		display: flex;
		flex-direction: column;
		height: 100vh;
	}

	.main-content {
		// display: flex;
		// transform: translateY(-48rpx);
		// height: calc(100% + 48rpx);
		overflow: hidden;
		/* #ifdef MP-WEIXIN */
		flex: 1;
		/* #endif */
	}

	.head-box {
		width: 100%;
		padding-bottom: 18rpx;
		display: flex;
		flex-direction: column;
		box-sizing: border-box;
		z-index: 99;

		.head-bg {
			position: absolute;
			z-index: -1;
			top: 0;
			left: 0;
			width: 100%;
		}





	}

	.team-list-item {
		margin-bottom: 16rpx;
	}

	.notice-content {
		width: 480rpx;
		padding: 20rpx 18rpx;
		background-color: #222528;
		border-radius: 16rpx;
		flex-direction: column;
		justify-content: space-between;

		.name {
			color: $title-color;
			font-size: 32rpx;
			box-sizing: border-box;
			text-align: center;
		}

		.notice-box {
			margin-top: 24rpx;


			.scroll-Y {
				width: 100%;
				max-height: 40vh;
			}

			.title {
				color: $title-color;
				font-size: 26rpx;
			}
		}

		.content {
			color: $description-color !important;
			font-size: 24rpx !important;
			margin-top: 32rpx;
			line-height: 32rpx !important;
		}

		.time {
			align-self: flex-end;
			color: $description-color;
			font-size: 24rpx;
			margin-top: 32rpx;

		}

		.content-box {
			flex-direction: column;
		}

		.notice-btn {
			width: 180rpx;
			height: 54rpx;
			background: $btn-bg-color;
			border-radius: 27rpx;
			color: $btn-text-color;
			font-size: 24rpx;
			text-align: center;
			line-height: 54rpx;
			margin-top: 24rpx;
		}
	}
</style>

<style>
	/deep/ .u-tabs__wrapper__nav {
		justify-content: space-between;
	}

	/deep/ .u-tabs__wrapper__nav__line {
		left: 0;
	}

	/deep/ .u-tabs__wrapper__nav__item {
		flex: 1;
	}
</style>